using AutoMapper;
using B.S.RbacData.ErrorCode;
using B.S.RbacData.Infrastructure;
using ContentmanagementBase.Domain;
using ContentmanagementBaseWrite.API.Applications.Commands.Hospitals;
using MediatR;

namespace ContentmanagementBaseWrite.API.Applications.Commandhandlters.Hospitals
{
    /// <summary>
    /// 更新医院命令处理器
    /// </summary>
    public class UpdateHospitalCommandHandler : IRequestHandler<UpdateHospitalCommand, ApiResult<int>>
    {
        /// <summary>
        /// 医院仓储
        /// </summary>
        private readonly IBaseRepository<HospitalManagementModel> _hospitalRepository;
        /// <summary>
        /// 映射器
        /// </summary>
        private readonly IMapper _mapper;
        /// <summary>
        /// 日志记录器
        /// </summary>
        private readonly ILogger<UpdateHospitalCommandHandler> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="hospitalRepository">医院仓储</param>
        /// <param name="mapper">映射器</param>
        /// <param name="logger">日志记录器</param>
        public UpdateHospitalCommandHandler(IBaseRepository<HospitalManagementModel> hospitalRepository, IMapper mapper, ILogger<UpdateHospitalCommandHandler> logger)
        {
            _hospitalRepository = hospitalRepository;
            _mapper = mapper;
            _logger = logger;
        }

        /// <summary>
        /// 处理更新医院命令
        /// </summary>
        /// <param name="request">请求</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns></returns>
        public async Task<ApiResult<int>> Handle(UpdateHospitalCommand request, CancellationToken cancellationToken)
        {
            try
            {
                _logger.LogInformation("开始处理医院更新命令，医院ID：{Id}，医院名称：{HospitalName}", request.Id, request.HospitalName);

                // 验证医院是否存在
                var existingHospital = _hospitalRepository.GetAll().FirstOrDefault(x => x.Id == request.Id);
                if (existingHospital == null)
                {
                    _logger.LogWarning("医院不存在，ID：{Id}", request.Id);
                    return new ApiResult<int>
                    {
                        code = ResultEnumCode.error,
                        message = "医院不存在！",
                        data = 0
                    };
                }

                // 验证医院名称是否与其他医院重复（排除自身）
                var existingHospitals = _hospitalRepository.GetAll()
                    .Where(x => x.HospitalName == request.HospitalName && x.Id != request.Id);

                if (existingHospitals.Any())
                {
                    _logger.LogWarning("医院名称已存在，名称：{HospitalName}", request.HospitalName);
                    return new ApiResult<int>
                    {
                        code = ResultEnumCode.error,
                        message = "医院名称已存在！",
                        data = 0
                    };
                }

                _logger.LogDebug("医院验证通过，开始更新医院信息");

                // 更新医院信息
                existingHospital.HospitalName = request.HospitalName;
                existingHospital.HospitalImage = request.HospitalImage;
                existingHospital.HospitalGrade = request.HospitalGrade;
                existingHospital.HospitalType = request.HospitalType;
                existingHospital.IsRecommend = request.IsRecommend;
                existingHospital.DoctorsNum = request.DoctorsNum;
                existingHospital.DepartmentsNum = request.DepartmentsNum;
                existingHospital.HospitalDepartments = request.HospitalDepartments;
                existingHospital.HospitalAddress = request.HospitalAddress;
                existingHospital.HospitalPhone = request.HospitalPhone;
                existingHospital.InTheArea = request.InTheArea;
                existingHospital.HospitalIntroduction = request.HospitalIntroduction;
                existingHospital.UpdatedTime = DateTime.Now;
                existingHospital.UpdatedBy = 1; // 这里应该从当前用户上下文获取

                _logger.LogDebug("医院信息更新完成，准备保存到数据库");

                // 保存到数据库
                var result = await _hospitalRepository.UpdateAsync(existingHospital);
                _logger.LogInformation("数据库更新完成，影响行数：{Result}", result);

                if (result > 0)
                {
                    _logger.LogInformation("医院更新成功，ID：{Id}", request.Id);
                    return new ApiResult<int>
                    {
                        code = ResultEnumCode.Ok,
                        message = "医院更新成功",
                        data = request.Id
                    };
                }
                else
                {
                    _logger.LogWarning("医院更新失败，数据库未返回影响行数");
                    return new ApiResult<int>
                    {
                        code = ResultEnumCode.fails,
                        message = "医院更新失败",
                        data = 0
                    };
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "医院更新过程中发生异常，医院ID：{Id}", request.Id);
                return new ApiResult<int>
                {
                    code = ResultEnumCode.fails,
                    message = $"医院更新异常：{ex.Message}",
                    data = 0
                };
            }
        }
    }
}